var loanId = $("#loan").data("id"),
    loanStatus = $("#loan").data("status"),
    approveBtn = $("#loanApproveBtn"),
    loanRejectBtn = $("#loanRejectBtn"),
    auditComment = $("#auditComment"),
    loanAuditPanel = $("#loanAuditPanel"),
    loanAuditPanelDetail = $("#loanAuditPanelDetail"),
    loanAuditTitle = $("#loanAuditTitle"),
    loanSchedulePanel = $("#loanSchedulePanel"),
    loanSchedulePanelDetail = $("#loanSchedulePanelDetail"),
    loanScheduleTitle = $("#loanScheduleTitle"),
    calendarPanel = $("#calendarPanel"),
    toggleCalendarBtn = $("#toggleCalendarBtn"),
    loanStatusDesc = $("#loanStatusDesc"),
    finishCountDownPanel = $("#finishCountDownPanel"),
    finishCountDownPanelTitle = $("#finishCountDownPanelTitle"),
    finishCountDownPanelDetail = $("#finishCountDownPanelDetail"),
    settlePanel = $("#settlePanel"),
    settlePanelTitle = $("#settlePanelTitle"),
    timeFormat = "yyyy/MM/dd HH:mm",
    // 費率
    serviceFee = $("#serviceFee"),
    guaranteeFee = $("#guaranteeFee"),
    manageFee = $("#manageFee"),
    investFee = $("#investFee"),
    currLoan;

$(function () {
    /**
     * 载入标的信息
     */
    var loadLoanInfo = function () {
        if (loanId && loanId !== '') {
            $.get("loan/getById/" + loanId, function (data) {
                if (data) {
                    var loan = data.loan, fee = data.fee;
                    // 显示标的信息
                    $("#title").html(loan.title || '标的名称未填写');
                    $("#amount").html($.number(loan.amount));
                    var percentage = (loan.investAmount / loan.amount * 100).toFixed(0) + '%';
                    $("#percentage").html(percentage);
                    $(".progress-bar").css("width", percentage);
                    $('.repayMethod').html(sys.getRepayMethod(loan.repayMethod));
                    $(".rate").html(parseFloat(loan.rate / 100).toFixed(1) + '%');
                    $("#duration").html(sys.printDuration(loan.duration));
                    $("#timeOut").html(loan.timeOut + '小时');
                    $("#submitTime").html($.format.date(loan.submitTime, timeFormat));
                    $("#loanProduct").html(loan.loanProduct ? sysLoanProduct[loan.loanProduct] : "-");
                    $("#user").text(data.userLoginName);
                    $(".user-link").attr("href", "user/index/" + loan.userId);
                    $(".contractall-link").attr("href", "contract/getAllContractByJson/" + loan.id);
                    $("#realName").text(loan.user.name);
                    $("#idNumber").text(loan.user.idNumber);
                    $("#mobile").text(loan.user.mobile);

                    $("#minAmount").text(loan.investRule.minAmount);
                    $("#maxAmount").text(loan.investRule.maxAmount);
                    $("#stepAmount").text(loan.investRule.stepAmount);
                    // 标的费率
                    serviceFee.text(fee.serviceFee * 10000 / 100 + '%');
                    guaranteeFee.text(fee.guaranteeFee * 10000 / 100 + '%');
                    manageFee.text(fee.manageFee * 10000 / 100 + '%');
                    investFee.text(fee.investFee * 10000 / 100 + '%');

                    if (loan.description && loan.description !== '') {
                        $("#description .display").html(loan.description);
                    } else {
                        $("#description .display").html("未填写");
                    }
                    if (loan.contractproperty && loan.contractproperty !== '') {
                        $("#contractproperty .display").html(loan.contractproperty);
                    } else {
                        $("#contractproperty .display").html("未填写");
                    }
                    if (loan.guaranteeInfo && loan.guaranteeInfo !== '') {
                        $("#guaranteeInfo .display").html(loan.guaranteeInfo);
                    } else {
                        $("#guaranteeInfo .display").html("未填写");
                    }
                    if (loan.mortgageInfo && loan.mortgageInfo !== '') {
                        $("#mortgageInfo .display").html(loan.mortgageInfo);
                    } else {
                        $("#mortgageInfo .display").html("未填写");
                    }
                    loanStatusDesc.text(sys.getLoanStatusDesc(loan.status));

                    // 根据标的状态显示操作面板
                    if (loan.status === 'PROPOSED' || loan.status === 'REJECTED') {
                        auditComment.val(loan.auditInfo);
                        // 显示审核面板
                        bindAuditActions();
                    } else if (loan.status === 'APPROVED') {
                        // 已批准状态显示排期日历
                        initCalendar();
                    } else if (loan.status === 'SCHEDULED') {
                        // 已排期状态显示开标倒计时
                        var openTime = new Date(loan.openTime);
                        initCalendar(openTime);
                        $("#openHour").val(openTime.getHours());
                        $("#openMin").val(openTime.getMinutes());
                        initOpenCountDown(loan);
                    } else if (loan.status === 'OPEN') {
                        // 开标状态显示结标倒计时
                        initFinishCountDown(loan);
                    } else if (["FINISHED", "FAILED", "LOANED", "CLEARED"].indexOf(loan.status) !== -1) {
                        // 结标状态显示结标时间
                        initFinishTime(loan);
                    }
                    currLoan = loan;
                    initEditor();
                    $("#description .summernote").code(loan.description);
                    $("#contractproperty .summernote").code(loan.contractproperty);
                    $("#guaranteeInfo .summernote").code(loan.guaranteeInfo);
                    $("#mortgageInfo .summernote").code(loan.mortgageInfo);
                    
                    makeOperations(loan);
                    if(loan.status==="LOANED"){
                        $(".openEditor").hide();
                    }
                    if(loan.status==="FINISHED"){
                        $(".contrac_button").hide();
                    }
                }
            });
        }
    };

    var initPage = function () {
        // 更新tab状态
        $("#tab-detail").removeClass("btn-default").addClass("btn-primary");
        // 更新标的列表链接，标的状态
        $(".returnLoanListLink").attr("href", "loan/list/" + loanStatus.toLowerCase());
        // 载入标的信息
        loadLoanInfo();
        initEvents();
    };

    // 初始化页面
    initPage();
});

function initEvents() {
    $(".openEditor").on("click", function () {
        $("#loan-desc .tab-pane.active .display").hide();
        $("#loan-desc .tab-pane.active .editor").show();
        $(this).hide();
        $("#loan-desc .tab-pane.active .hiddenEditor").show();
    });
    $(".cancelEditDesc").on("click", function () {
        $("#loan-desc .tab-pane.active .editor").hide();
        $("#loan-desc .tab-pane.active .display").show();
        $("#loan-desc .tab-pane.active .hiddenEditor").hide();
        $("#loan-desc .tab-pane.active .openEditor").show();
    });
    $(".saveEditDesc").on("click", function () {
        var content = $("#loan-desc .tab-pane.active .summernote").code(),
            url = $(this).data("url");
        $.post(url, {
            id: loanId,
            content: content
        }, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("网络通信错误");
        });
    });
}

/**
 * 初始化富文本编辑器
 */
function initEditor() {
    var height = 500;
    $(".summernote").summernote({
        height: height, //set editable area's height
        focus: false, //set focus editable area after Initialize summernote
        lang: 'zh-CN',
        fontNames: [
            'Microsoft Yahei', 'Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
            'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande'
        ],
//        toolbar: [
//            ['style', ['bold', 'italic', 'underline', 'clear']],
//            ['font', ['strikethrough', 'superscript', 'subscript']],
//            ['fontsize', ['fontsize']],
//            ['fontname', ['fontname']],
//            ['color', ['color']],
//            ['para', ['ul', 'ol', 'paragraph']],
//            ['height', ['height']],
//            ['Insert', ['link', 'table', 'hr']],
//            ['codeview', ['codeview']],
//            ['fullscreen', ['fullscreen']]
//        ]

        onImageUpload: function (files, editor, welEditable) {
            /**
             * 图片直接上传到upyun
             */
            var url = 'store/upload';
            var formData = new FormData(), document = files[0];
            formData.append("file", document);
            formData.append("name", document.name + '_' + (new Date()).getTime());
            formData.append("desc", "");
            formData.append("realm", 'IMAGE');
            formData.append("id", loanId);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    if (res.success) {
                        editor.insertImage(welEditable, res.message);
                        imgUrl = res.message;
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('图片上传失败：服务器错误');
            });
        }
    });
    $('.note-editable').css('font-size', '18px');
}

/**
 * 显示标的审核通过面板并绑定审核按钮事件
 */
function bindAuditActions() {
    loanAuditPanel.removeClass("hidden");
    approveBtn.on("click", function () {
        if (confirm("确定批准标的？")) {
            $.get("loan/approve/" + loanId, function (success) {
                if (success) {
                    alert("标的批准成功");
                    location.reload();
                } else {
                    alert("标的批准失败");
                }
            });
        }
    });
    loanRejectBtn.on("click", function () {
        if (confirm("确定驳回标的？")) {
            $.post("loan/rejectLoan", {
                id: loanId,
                auditInfo: auditComment.val()
            }, function (res) {
                if (res) {
                    alert("标的驳回成功");
                    location.reload();
                } else {
                    alert("标的驳回失败");
                }
            });
        }
    });
}
/**
 * 显示审核通过状态
 */
function markAudit() {
    loanAuditTitle.text("标的审核已通过");
    loanAuditPanelDetail.remove();
    loanAuditPanel.removeClass("hidden");
}
/**
 * 初始化标的排期日历
 */
function initCalendar(default_date) {
    markAudit();
    var loanOpenTimePicker = $('#loanOpenTimePicker');
    loanOpenTimePicker.datepicker({
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        showButtonPanel: false,
        controlType: 'select',
        oneLine: true,
        timeText: '标的开标时间：',
        hourText: '选择开标时：',
        minuteText: '选择开标分：',
        minDate: 0//不可选择今日之前的日期
    });
    // 设置当前时间
    loanOpenTimePicker.datepicker('setDate', default_date ? default_date : (new Date()));
    //loanOpenTimePicker.datetimepicker('setDate', default_date ? default_date : (new Date()));

    if (default_date) {
        $('#scheduleLoanBtn').text("修改开标时间");
        calendarPanel.addClass("hidden");
        toggleCalendarBtn.on("click", function () {
            calendarPanel.toggleClass("hidden");
        }).removeClass("hidden");
    }

    var openHour = $("#openHour"), openMin = $("#openMin");
    // 确定排期按钮
    $('#scheduleLoanBtn').click(function () {
        var date = loanOpenTimePicker.datepicker('getDate');
        date = new Date(date);
        date.setHours(openHour.val());
        date.setMinutes(openMin.val())
        dateString = $.format.date(date.getTime(), timeFormat);
        if (confirm("开标时间确认为：" + dateString + "？")) {
            $.post("loan/schedule", {
                id: currLoan.id,
                openTime: date
            }, function (res) {
                if (res.success) {
                    alert("标的排期成功！开标时间为：" + dateString);
                    location.reload();
                } else {
                    alert("标的排期失败");
                }
            });
        }
    });
    loanSchedulePanel.removeClass("hidden");
}
/**
 * 显示已排期状态
 */
function markScheduled(openTime, editable) {
    if (!editable) {
        $("#loanSchedulePanelDetail .admin-form").remove();
    }
    loanScheduleTitle.text("开标时间为：" + $.format.date(openTime, timeFormat));
    loanSchedulePanel.removeClass("hidden");
}
/**
 * 显示开标倒计时
 */
function initOpenCountDown(loan) {
    markAudit();
    var openTime = new Date(loan.openTime);
    $("#openCountDown").removeClass("hidden").countdown(openTime, function (event) {
        if (event.offset.totalDays > 0) {
            $(this).html(event.strftime('<code class="fs12 mr10">开标倒计时</code>%-D <span class="fs12">天</span> %H:%M:%S'));
        } else {
            $(this).html(event.strftime('<code class="fs12 mr10">开标倒计时</code> %H:%M:%S'));
        }
    });
    markScheduled(openTime, true);
}
function markFinished(text) {
    finishCountDownPanelTitle.text(text);
    finishCountDownPanel.removeClass("hidden");
}
/**
 * 显示结标倒计时
 */
function initFinishCountDown(loan) {
    markAudit();
    var openTime = new Date(loan.openTime),
        timeOut = loan.timeOut,
        finishTime = new Date(loan.openTime + timeOut * 60 * 60 * 1000);
    // 显示开标时间
    markScheduled(openTime);
    // 初始化结标倒计时
    $("#finishCountDown").countdown(finishTime, function (event) {
        if (event.offset.totalDays > 0) {
            $(this).html(event.strftime('<code class="fs12 mr10">结标倒计时</code>%-D <span class="fs12">天</span> %H:%M:%S'));
        } else {
            $(this).html(event.strftime('<code class="fs12 mr10">结标倒计时</code> %H:%M:%S'));
        }
    });
    markFinished("开放投标中（筹款时长：" + timeOut + "小时）");
}
/**
 * 显示结标时间
 */
function initFinishTime(loan) {
    markAudit();
    var openTime = new Date(loan.openTime),
        finishTime = loan.finishTime === null ? "未知" : $.format.date(new Date(loan.finishTime), timeFormat);
    markScheduled(openTime);
    finishCountDownPanelDetail.remove();
    markFinished("投标结束时间：" + finishTime);
    // 显示放款时间
    if (loan.status !== 'FINISHED' && loan.status !== 'FAILED') {
        var loanTime = new Date(loan.loanTime);
        settlePanelTitle.text("标的放款时间：" + $.format.date(loanTime, timeFormat));
        settlePanel.removeClass("hidden");
    }
}
/**
 * 根据不同状态显示不同操作
 */
function makeOperations(loan) {
    if (loanStatus === 'PROPOSED' || loanStatus === 'REJECTED') {
        $(".detailLink a").html('<i class="fa fa-legal mr5"></i>标的审核');
        $(".divider").removeClass("extra hidden");
        $(".contractall-status").addClass("hidden");
    } else if (loanStatus === 'APPROVED') {
        $(".detailLink a").html('<i class="fa fa-clock-o mr5"></i>标的排期');
        $(".divider").removeClass("extra hidden");
        $(".contractall-status").addClass("hidden");
    } else if (loanStatus === 'SCHEDULED') {
        $(".detailLink a").html('<i class="glyphicons glyphicons-restart mr5"></i>重新排期');
        $(".cancelScheduleLink").removeClass("extra hidden");
        $(".contractall-status").addClass("hidden");
    } else if (loanStatus === 'OPEN') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".divider").removeClass("extra hidden");
        $(".contractall-status").addClass("hidden");
    } else if (loanStatus === 'FINISHED') {
        $(".settleLink").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (loanStatus === 'FAILED') {
        if (loan.investAmount !== 0) {
            $(".settleLink").removeClass("extra hidden");
        }
    } else if (loanStatus === 'LOANED') {
        $(".repayment").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (loanStatus === 'OVERDUE') {
        $(".repayment a").attr("href", "repayment/overdue");
        $(".repayment").removeClass("extra hidden");
        $(".cancelLink").addClass("hidden");
    } else if (loanStatus === 'CANCELED') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".cancelLink").addClass("hidden");
    } else if (loanStatus === 'CLEARED') {
        $(".cancelLink").addClass("hidden");
        $(".archiveLink").removeClass("extra hidden");
    } else if (loanStatus === 'ARCHIVED') {
        $(".editLink a").html('<i class="glyphicons glyphicons-edit mr5"></i>部分编辑');
        $(".cancelLink").addClass("hidden");
    }
    if (sysEditableStatus.indexOf(loanStatus) !== -1) {
        $(".editLink").removeClass("extra hidden");
    }
    if (sysPartlyEditableStatus.indexOf(loanStatus) !== -1) {
        $(".editLink").removeClass("extra hidden");
    }
    $("li.extra").remove();
    // 替换#id为loan.Id
    $("#operationHTML").html($("#operationHTML").html().replace(/#id/g, loanId));
}
/**
 * 取消标的排期
 */
function cancelSchedule(a) {
    if (confirm("确定取消标的排期？取消后标的将打回【已批准】列表")) {
        var id = $(a).data("id");
        $.get("loan/cancelSchedule/" + id, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器异常");
        });
    }
}
/**
 * 取消标的
 */
function cancel(a) {
    sys.confirm("确定取消标的？取消后标的将放入【已取消】列表，已募集资金会退还给投资人", function () {
        var id = $(a).data("id");
        sys.processModal();
        $.get("loan/cancel/" + id, function (res) {
            if (res.success) {
                alert("标的已取消");
                location.reload();
            } else {
                alert("标的取消失败");
                sys.closeModal();
            }
        }).fail(function () {
            alert("网络通信错误");
            sys.closeModal();
        });
    });
}
/**
 * 存档标的
 */
function archive(a) {
    if (confirm("确定存档标的？存档后标的在前台不再显示")) {
        var id = $(a).data("id");
        $.get("loan/archive/" + id, function (res) {
            if (res.success) {
                alert(res.message);
                location.reload();
            } else {
                alert(res.message);
            }
        }).fail(function () {
            alert("网络通信错误")
        });
    }
}
/**
 * 标的放款
 */
function settleLoan(a) {
    if (confirm("确定放款？")) {
        $.magnificPopup.open({
            removalDelay: 500, //delay removal by X to allow out-animation,
            alignTop: true,
            closeOnBgClick: false,
            items: {
                src: "#modal"
            },
            // overflowY: 'hidden', // 
            callbacks: {
                beforeOpen: function (e) {
                    this.st.mainClass = 'mfp-slideDown';
                }
            },
            midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
        });

        var id = $(a).data("id");
        $.post("loan/loan", {
            id: id
        }, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
            $.magnificPopup.close();
        }).fail(function () {
            alert("服务器错误");
            $.magnificPopup.close();
        });
    }
}
